package com.example.gbb.adapters;

import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.gbb.R;
import com.example.gbb.bean.ItemBean;

import java.util.List;

public abstract class RecyclerViewBaseAdapter extends RecyclerView.Adapter<RecyclerViewBaseAdapter.InnerHoldler> {

    private  List<ItemBean> list;
    private OnItemClickListener mOnItemClickListener;

    public RecyclerViewBaseAdapter(List<ItemBean> list){
        this.list = list;
    }

    /**
     * 获取条目布局，使用抽象的方法实现在子中重写这个方法重而实现加载不同的布局(ListView,GridView和瀑布流)
     * @param parent
     * @param viewType
     * @return
     */
    @NonNull
    @Override
    public InnerHoldler onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //调用getSubView抽象方法获取条目布局
        View view = getSubView(parent,viewType);
        return new InnerHoldler(view);
    }

    //在子类中重写这个方法返回一个包含了条目布局的View
    protected abstract View getSubView(ViewGroup parent,int viewTyoe);

    /**
     * 调用setData方法，使条目控件绑定数据
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(@NonNull InnerHoldler holder, int position) {
        holder.setData(list.get(position),position);

    }

    /**
     * 返回条目个数
     * @return
     */
    @Override
    public int getItemCount() {
        if(list != null){
            return list.size();
        }
        return 0;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        //设置监听，设置一个接口，回调的接口
        this.mOnItemClickListener = listener;

    }

    /**
     * 创建回调接口的步骤
     * 1.创建这个接口
     * 2.定义接口内部的方法
     * 3.外部设置接口
     * 4.接口方法的调用
     */
    public interface OnItemClickListener{
        void onItemClick(int position);

    }

    public class InnerHoldler extends RecyclerView.ViewHolder {
        private ImageView icon;
        private TextView title;
        private int mposition;

        public InnerHoldler(@NonNull View itemView) {
            super(itemView);
            //绑定条目控件
            icon = (ImageView)itemView.findViewById(R.id.icon);
            title = (TextView)itemView.findViewById(R.id.title);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(mOnItemClickListener != null){
                        mOnItemClickListener.onItemClick(mposition);
                    }
                }
            });
        }

        //条目控件绑定数据
        public void setData(ItemBean itemBean,int position) {
            this.mposition = position;
            icon.setImageResource(itemBean.icon);
            title.setText(itemBean.title);
        }
    }
}
